from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import sys
import time
import random,datetime
import LoadAllData,threading
lock = threading.RLock()
okex_dic={}


web_name = ['Okex', 'Bittrex','Binance', 'Bitfinex','Bcex','ZB', ]

my_all_keys = ['刷新','btc', 'eth', 'etc', 'bch', 'ltc', 'xrp', 'neo', 'qtum', 'dash', 'xem', 'xlm', 'salt', 'rfr', 'zen',
               'enj', 'dcr', 'dgb' , 'storj', 'lrc', 'pax', 'rcn', 'tusd', 'sc', 'mtl', 'gto', 'lsk', 'pay', 'eng', 'ada', 'dnt', 'zec', 'ardr', 'snt',
               'mco'    , 'bkx', 'zrx', 'nxt', 'ngc', 'cvc', 'mana', 'ark', 'xmr', 'gnt', 'bnt', 'waves', 'omg', 'trx', 'vib', 'mith',
               'xuc','fun', 'topc', 'edo', 'xwc', 'eos', 'chat', 'true', 'doge', 'btm', 'ae', 'qun', 'kan', 'sub', '1st',
                'edo','fun','eos','ae','sub','knc','icx','xvg' ,'sys','oax','ins','via','mft','rdn','lun','adx','poe','grs','steem',
               'nano','nav','nxs','ost','rlc','loom','bat','powr','nas','mda','evx','cloak','go','key','yoyo','itc','iota','dent'
               ,'tnb','req','zil','sngls','dgd','wtc','iost','pivx','bcd','bcpt','link','storm','kmd','nuls','strat','btg','wings',
               'rep','ont','ast','poly','lend','cmt','gas','xzc','rvn','elf','ppt','npxs','int','utk','wpr','wax','dat','avt','vet',
               'san','bft','aid','dta','vee','ant','mln','cnd','cbt','hot','mkr','agi','dct','fct','aion','aidoc','cit','lmc']
def loadalldata():
    LoadAllData.start_load_data()

isOkexOut=False
isBittrexOut=False
isBinanceOut=False
isBitfinexOut=False
isBcexOut=False
isZBOut=False

def change_show_data():
    LoadAllData.change_show_data(isOkexOut,isBittrexOut,isBinanceOut,isBitfinexOut,isBcexOut,isZBOut)

class MyTable(QTableWidget):
    def __init__(self, parent=None):
        super(MyTable, self).__init__(parent)

        self.setWindowTitle('ToggleButton')
        self.red = QPushButton('Okex', self)
        self.red.setCheckable(True)
        self.red.move(0, 0)
        self.red.clicked.connect(self.setOkex)
        self.green = QPushButton('Bittrex', self)
        self.green.setCheckable(True)
        self.green.move(70, 0)
        self.green.clicked.connect(self.setBittrex)
        self.blue = QPushButton('Binance', self)
        self.blue.setCheckable(True)
        self.blue.move(140, 0)
        self.blue.clicked.connect(self.setBinance)

        self.Bitfinex = QPushButton('Bitfinex', self)
        self.Bitfinex.setCheckable(True)
        self.Bitfinex.move(210, 0)
        self.Bitfinex.clicked.connect(self.SetBitfinex)

        self.Bcex = QPushButton('Bcex', self)
        self.Bcex.setCheckable(True)
        self.Bcex.move(280, 0)
        self.Bcex.clicked.connect(self.SetBcex)

        self.ZB = QPushButton('ZB', self)
        self.ZB.setCheckable(True)
        self.ZB.move(350, 0)
        self.ZB.clicked.connect(self.SetZB)

        print("width=%d" % self.frameGeometry().width())
        print("height=%d\n" % self.frameGeometry().height())

    def setOkex(self):
        global isOkexOut
        isOkexOut=self.red.isChecked()
        change_show_data()
        print('setOkex',self.red.isChecked())

    def setBittrex(self):
        global isBittrexOut
        isBittrexOut=self.green.isChecked()
        change_show_data()
        print('setBittrex', self.green.isChecked())

    def setBinance(self):
        global isBinanceOut
        isBinanceOut =self.blue.isChecked()
        change_show_data()
        print('setBinance', self.blue.isChecked())

    def SetBitfinex(self):
        global  isBitfinexOut
        isBitfinexOut = self.Bitfinex.isChecked()
        change_show_data()
        print('SetBitfinex', self.Bitfinex.isChecked())

    def SetBcex(self):
        global  isBcexOut
        isBcexOut = self.Bcex.isChecked()
        change_show_data()
        print('SetBcex', self.Bcex.isChecked())
    def SetZB(self):
        global  isZBOut
        isZBOut = self.ZB.isChecked()
        change_show_data()
        print('SetZB', self.ZB.isChecked())

    def showwindow(self, keys):
        self.setWindowTitle("市场行情")  # 设置表格名称
        self.setWindowIcon(QIcon("ok.png"))  # 设置图标（图片要存在）
        self.resize(1200, 600)  # 设置表格尺寸（整体大小）
        # myTable.verticalHeader().setFixedWidth(300)
        # row_name = [
        #     'Okex',
        #     'Bittrex',
        #     'ZB',
        # ]

        self.setColumnCount(len(web_name))  # 设置列数
        self.setRowCount(len(keys))  # 设置行数
        # self.setColumnWidth(0, 180)  # 设置列宽(第几列， 宽度)
        # # self.setRowHeight(0, 20)  # 设置行高(第几行， 行高)
        # self.setColumnWidth(1, 220)  # 设置列宽(第几列， 宽度)
        # self.setColumnWidth(2, 220)  # 设置列宽(第几列， 宽度)
        if isOkexOut:
            self.setColumnWidth(0, 0)
        else:
            self.setColumnWidth(0, 180)
        if isBittrexOut:
            self.setColumnWidth(1, 0)
        else:
            self.setColumnWidth(1, 205)
        if isBinanceOut:
            self.setColumnWidth(2, 0)
        else:
            self.setColumnWidth(2, 205)
        if isBitfinexOut:
            self.setColumnWidth(3, 0)
        else:
            self.setColumnWidth(3, 205)
        if isBcexOut:
            self.setColumnWidth(4, 0)
        else:
            self.setColumnWidth(4, 205)
        if isZBOut:
            self.setColumnWidth(5, 0)
        else:
            self.setColumnWidth(5, 205)


        # for i, v in enumerate(web_name):
        #     if i == 0:
        #         self.setColumnWidth(0, 180)
        #     else:
        #         self.setColumnWidth(i, 220)

        # row_name=list(okex_dic[1])
        # print("-->",len(row_name))
        column_name = [
        ]
        self.setHorizontalHeaderLabels(web_name)  # 设置列名称
        self.setVerticalHeaderLabels(keys)  # 设置行名称

    def update_item_data(self, data):
        """更新内容"""
        print('刷新')
        self.setItem(0, 0, QTableWidgetItem(data))  # 设置表格内容(行， 列) 文字
        self.showwindow(my_all_keys)
        lock.acquire()
        try:
            set_keys = list(set(LoadAllData.all_keys_list))
            # for i in set_keys:
            #     print(i.upper())

            for i in set_keys:
                if i not in my_all_keys:
                    my_all_keys.append(i)
            self.showwindow(my_all_keys)

            for i, key in enumerate(my_all_keys):
                for j, web in enumerate(web_name):
                    itemdata_1 = LoadAllData.all_datas[web].get(key)
                    if itemdata_1 is not None:
                        strs_btc = '%.8f' % (itemdata_1['btc'])
                        # pre=itemdata_1['precent']*100
                        pre = round(itemdata_1['precent'] * 100, 2)
                        value_usdt = round(itemdata_1['usdt'], 4)
                        showstr = ''
                        if pre == 0:
                            showstr = "[$" + str(value_usdt) + "][B" + strs_btc + ']'
                        else:
                            showstr = "[$" + str(value_usdt) + "][B" + strs_btc + ']' + '[' + str(pre) + '%]'

                        self.newItem = QTableWidgetItem(str(showstr))

                        self.setItem(i, j, self.newItem)
                        if itemdata_1['precent'] < -0.02:
                            self.newItem.setBackground(QColor('Lime'))
                        if itemdata_1['precent'] > 0.02:
                            self.newItem.setBackground(QColor('Red'))


                    else:
                        pass
        except:
            print('刷新UI Error')

        lock.release()

class UpdateData(QThread):
    """更新数据类"""
    update_date = pyqtSignal(str)  # pyqt5 支持python3的str，没有Qstring

    def run(self):
        cnt = 0
        while True:
            cnt += 1
            nowTime=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            self.update_date.emit(str(nowTime))  # 发射信号
            time.sleep(3)


if __name__ == '__main__':
    loadalldata()
    # 实例化表格
    app = QApplication(sys.argv)
    myTable = MyTable()
    # myTable.horizontalHeader().setDefaultSectionSize(100)
    myTable.horizontalHeader().setFixedHeight(60)
    myTable.verticalHeader().setDefaultSectionSize(25)

    font = myTable.horizontalHeader().font()
    font.setBold(True)
    myTable.horizontalHeader().setFont(font)
    myTable.verticalHeader().setFont(font)
    # 启动更新线程
    update_data_thread = UpdateData()
    update_data_thread.update_date.connect(myTable.update_item_data)  # 链接信号
    update_data_thread.start()

    # 显示在屏幕中央
    # desktop = QApplication.desktop()  # 获取坐标
    # x = (desktop.width() - myTable.width()) // 2
    # y = (desktop.height() - myTable.height()) // 2
    # myTable.move(x, y)  # 移动

    screen = QDesktopWidget().screenGeometry()

    myTable.move((screen.width() - myTable.width()) / 2,
              (screen.height() - myTable.height()) / 2)


    # 显示表格
    myTable.show()
    app.exit(app.exec_())

